﻿using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Mvc.Binders;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace CRM.Admin.Areas.Sys.Controllers
{
    public class MenuController : Controller
    {
        /// <summary>
        /// 菜单-业务操作契约
        /// </summary>
        public IMenuService _Menuservice { get; set; }

        public ActionResult MenuIndex()
        {
            return View();
        }
        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuNodeAdd()
        {
            return View();
        }

        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuNodeEdit(Guid MenuNodeId)
        {
            var node = _Menuservice.MenuNodes.
                FirstOrDefault(entity => entity.Id == MenuNodeId);
            string power = "";
            foreach (var action in node.Actions)
            {
                power += power != "" ? "," + action.Code + ":" + action.Name : action.Code + ":" + action.Name;
            }
            MenuNodeDto dto = node.MapTo<MenuNodeDto>();
            dto.ActionPower = power;

            return View(dto);
        }

        /// <summary>
        /// 新增菜单目录
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuCatalogAdd()
        {
            return View();
        }
        /// <summary>
        /// 编辑菜单目录
        /// </summary>
        /// <param name="CatalogId"></param>
        /// <returns></returns>
        public ActionResult MenuCatalogEdit(Guid CatalogId)
        {
            return View(_Menuservice.MenuCatalogs.Where(entity => entity.Id == CatalogId).
                FirstOrDefault().MapTo<MenuCatalogDto>());
        }
        /// <summary>
        /// 目录菜单树
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuTree(int Type = -1)
        {

            var data = _Menuservice.MenuCatalogs
            .Select(entity => new
            {
                entity.Name,
                entity.Type,
                Pid = entity.ParentMenuCatalog != null ? entity.ParentMenuCatalog.Id.ToString() : "root_" + entity.Type,
                entity.Id,
                entity.Order,
                entity.IsDeleted
            })
                .Where(entity => entity.IsDeleted == false && (Type != -1) ? entity.Type == Type : true).OrderBy(entity => entity.Type).OrderByDescending(entity => entity.Order)
            .ToList();
            List<object> rootData = new List<object>();
            typeof(SystemMenuType).Each((name, value, dic) =>
            {
                if (Type != -1)
                {
                    if (int.Parse(value) == Type)
                    {
                        var tempData = new
                        {
                            Name = "<span style='color:red'>" + dic + "</span>",
                            Type = short.Parse(value),
                            Id = "root_" + value,
                            Pid = 0,
                            Order = int.Parse(value),
                            open = true,
                            isRoot = true
                        };
                        rootData.Add(tempData);
                    }
                }
                else
                {
                    var tempData = new
                    {
                        Name = "<span style='color:red'>" + dic + "</span>",
                        Type = short.Parse(value),
                        Id = "root_" + value,
                        Pid = 0,
                        Order = int.Parse(value),
                        open = true,
                        isRoot = true
                    };
                    rootData.Add(tempData);
                }
            });
            ViewBag.CatalogData = data.ToJsonString();
            ViewBag.RootData = rootData.ToJsonString();
            return View();
        }
        #region 数据功能

        /// <summary>
        /// 菜单目录-保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MenuCatalogInsert([ModelBinder(typeof(JsonBinder<MenuCatalogDto>))] MenuCatalogDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = _Menuservice.AddMenuCatalog(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "目录“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 修改菜单目录数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInputAttribute(false)]
        public ActionResult MenuCatalogUpdate([ModelBinder(typeof(JsonBinder<MenuCatalogDto>))] MenuCatalogDto dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = _Menuservice.EditMenuCatalog(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "目录“{0}”更新成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 保存菜单数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInputAttribute(false)]
        public ActionResult MenuNodeInsert([ModelBinder(typeof(JsonBinder<MenuNodeDto>))] MenuNodeDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = _Menuservice.AddMenuNode(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "菜单“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 更新菜单数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInputAttribute(false)]
        public ActionResult MenuNodeUpdate([ModelBinder(typeof(JsonBinder<MenuNodeDto>))] MenuNodeDto dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = _Menuservice.EditMenuNode(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "菜单“{0}”更新成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 分页获取菜单数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenuGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<MenuNode, bool>> predicate = FilterHelper.GetExpression<MenuNode>(request.FilterGroup);
            int total;
            var data = _Menuservice.MenuNodes.
                Where<MenuNode, Guid>(predicate, request.PageCondition, out total).
                Where(a => a.IsDeleted == false).
                Select(dto => new
                {
                    dto.Id,
                    dto.Name,
                    dto.IsDeleted,
                    dto.IconColor,
                    dto.IconText,
                    dto.MenuURL,
                    dto.Description,
                    dto.Order,
                    CatalogName = dto.MenuCatalog.Name,
                    Actionpower = dto.Actions.Select(a => new { a.Name }) //Actionpower=dto.Actions
                }).ToList();
            return Json(new GridData<object>(data, total), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Ajax获取所有目录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCatologTree()
        {
            var data = _Menuservice.MenuCatalogs
                       .Select(entity => new
                       {
                           entity.Name,
                           entity.Type,
                           Pid = entity.ParentMenuCatalog != null ? entity.ParentMenuCatalog.Id.ToString() : "root_" + entity.Type,
                           entity.Id,
                           entity.Order,
                           entity.IsDeleted
                       })
                       .Where(entity => entity.IsDeleted == false).OrderBy(entity => entity.Type).OrderByDescending(entity => entity.Order)
                       .ToList();
            List<object> rootData = new List<object>();
            typeof(SystemMenuType).Each((name, value, dic) =>
            {
                var tempData = new
                {
                    Name = "<span style='color:red'>" + dic + "</span>",
                    Type = short.Parse(value),
                    Id = "root_" + value,
                    Pid = 0,
                    Order = int.Parse(value),
                    open = true,
                    isRoot = true
                };
                rootData.Add(tempData);
            });
            var newData = new { menudata = data, rootdata = rootData };
            return Json(newData, JsonRequestBehavior.AllowGet);

        }
        #endregion
    }
}